<?php
/**
 * Created by PhpStorm.
 * User: zhan
 * Date: 2018/5/23  15:43
 */
namespace app\admin\Controller;
use think\Controller;
require __DIR__.'/Common.php';

class Article extends Common
{
    public function __construct()
    {
        parent::__construct();
    }
    
    public function index()
    {
        $pageParam = ['query' =>[]];

        $where = '';
        $title = input('title');
        if( $title != ''){
            $where['title'] = array('like','%'.$title.'%');
            $pageParam['query']['title'] = $title;
        }

        $type = input('type')?input('type'):'';
        if($type != ''){
            $where['type'] = $type;
            $pageParam['query']['type'] = $type;
        }
        $data = db('article')
            ->order('id desc')
            ->where($where)
            ->paginate(10, false, $pageParam);
        $page = $data->render();

        $this->assign('title', $title);
        $this->assign('type', $type);
        $this->assign('data', $data);
        $this->assign('page', $page);
        return $this->fetch();
    }

    /**
     *添加表单
     */
    public function add_article()
    {
        return $this->fetch();
    }

    /**
     * 编辑、添加
     */
    public function edit_article()
    {
        $id = input('id');
        $article = db('article');
        if(request()->isPost())
        {
            $data['title'] = input('title');
            $data['content'] = input('content');
            $data['type'] = input('type');
            $file=request()->file('image');
            if($file)
            {
                $info = $file->move(ROOT_PATH . 'public' . DS . 'static' . DS . 'uploads');
                if($info)
                {
                    $data['img']= $info->getSaveName();
                }
            }

            if($id)
            {
//                echo 'aa';exit;
                //修改
                $res = $article->where('id', $id)->update($data);
//                $sql = $article->getLastSql();
//                echo $sql;exit;
                if($res){$this->success('操作成功', url('article/index'));}else{$this->success('操作失败');}

            }else{
                //添加
                $res = $article->insert($data);
                if($res){$this->success('操作成功', url('article/index'));}else{$this->success('操作失败');}
            }
        }

        $data = $article->where('id', $id)->find();
        $this->assign('data', $data);
        return $this->fetch();
    }

    /**
     * 删除
     */
    public function del_article(){
        $id = input("id");
//        $this->success($id);
        if(!$id) $this->error('参数有误');
        $da=db('article')->where('id', $id)->find();
        if($da['img']) {
            $pic = ROOT_PATH . 'public/static/uploads/'.$da['img'];
            unlink($pic);
        }
        $res=db('article')->where("id='$id'")->delete();
        if(!$res) $this->error('删除失败');
        $this->success("删除成功!",url('article/index'));
    }
}